package cn.js.sangu.unitStore.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.List;

/**
 * 说明：PDF工具
 * 作者：linshuo
 * 日期：2024/12/9 12:33
 */
@Slf4j
public class PDFUtil {

    public static void mergePdf(File[] pdfFiles,String resPath) throws Exception {
        Document document = new Document();
        document.setMargins(0, 0, 0, 0);
        // ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStream bos = new FileOutputStream(resPath);

        PdfCopy copy = new PdfCopy(document, bos);
        document.open();
        for (File file : pdfFiles) {
            PdfReader reader = new PdfReader(file.getAbsolutePath());
            copy.addDocument(reader);
            copy.freeReader(reader);
            reader.close();
        }
        document.close();
    }

    public static void mergeToPDF(List<String> sources,String resPath){

        /**
         * pdf合并
         * @param inputStreams 要合并的pdf的InputStream数组
         * @return 合并后的pdf的二进制内容
         */
        try {
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(resPath));
            document.open();
            //遍历多个pdf源文件
            for (String pdf : sources) {
                //读者对象
                PdfReader reader = new PdfReader(pdf);
                //每个pdf的页数
                for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                    //新建页对象
                    document.newPage();
                    //放入目标对象
                    copy.addPage(copy.getImportedPage(reader, i));
                }
                //关闭读者
                reader.close();
            }
            //关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
